package com.skit.mine.fragment;

import android.app.ProgressDialog;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.skit.common.ResourcesManager;
import com.skit.common.bean.Department;
import com.skit.common.bean.Specialities;
import com.skit.common.bean.StatusResult;
import com.skit.common.bean.User;
import com.skit.common.bean.UserInfo;
import com.skit.common.config.RetrofitClient;
import com.skit.common.dialog.EditTextDialog;
import com.skit.common.http.HttpUtils;
import com.skit.common.manager.UserManager;
import com.skit.common.utils.TextUtils;
import com.skit.common.utils.ToastUtils;
import com.skit.mine.R;
import com.skit.mine.adapter.SingleTextAdapter;
import com.skit.mine.adapter.SingleTextAdapter2;
import com.skit.common.retrofit.UserProtocol;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;

/**
 * @author shuike <a href="mailto:shuike007@gmail.com">Contact me.</a>
 * @version 1.0
 * @since 2020/5/23
 */
public class DepartmentBottomSheetFragment extends BottomSheetDialogFragment {
    private static final String TAG = "DepartmentBottomSheetFr";
    private RecyclerView recyclerView, recyclerView2;
    private SingleTextAdapter adapter;
    private SingleTextAdapter2 adapter2;

    private List<Department> list = new ArrayList<>();
    private List<Specialities> list2 = new ArrayList<>();
    private Handler handler = new Handler();
    private ImageView back;
    private TextView title;
    private OnFinishListener onFinishListener;

    public interface OnFinishListener {
        void onFinish();
    }

    public void setOnFinishListener(OnFinishListener onFinishListener) {
        this.onFinishListener = onFinishListener;
    }

    public static DepartmentBottomSheetFragment newInstance() {

        Bundle args = new Bundle();

        DepartmentBottomSheetFragment fragment = new DepartmentBottomSheetFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.user_bottom_sheet_dialog_layout, container, false);
        recyclerView = inflate.findViewById(R.id.recyclerView);
        recyclerView2 = inflate.findViewById(R.id.recyclerView2);
        back = inflate.findViewById(R.id.back);
        title = inflate.findViewById(R.id.title);
        return inflate;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        User user = UserManager.getUser();
        if (user == null) {
            dismiss();
            return;
        }
        adapter = new SingleTextAdapter(list, 0);
        adapter2 = new SingleTextAdapter2(list2, 1);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView2.setLayoutManager(new LinearLayoutManager(getActivity()));

        recyclerView.setAdapter(adapter);
        recyclerView2.setAdapter(adapter2);

        adapter.setOnItemClickListener((data, position) -> {
            title.setText(data.getDepartmentName());
            recyclerView.setVisibility(View.GONE);
            recyclerView2.setVisibility(View.VISIBLE);
            list2.clear();
            list2.addAll(data.getSpecialitiesList());
            adapter2.notifyDataSetChanged();
        });

        adapter2.setOnItemClickListener(((data, position) -> {
            int did = list.get(adapter.getSelectPosition()).getId();
            int sid = data.getId();
            EditTextDialog editTextDialog = EditTextDialog.newInstance("请输入班号", "请输入班号");
            editTextDialog.setMaxLength(4);
            editTextDialog.setOnEditTextDialogListener(new EditTextDialog.OnEditTextDialogListener() {
                @Override
                public void onDone(String text) {
                    if (text == null || text.isEmpty()) {
                        editTextDialog.showError("内容不能为空");
                    } else if (!TextUtils.isNumber(text)) {
                        editTextDialog.showError("输入的内容必须为数字");
                    } else if (text.length() != 4) {
                        editTextDialog.showError("格式错误，格式为4位数字\n如: 1801");
                    } else {
                        setData(did, sid, Integer.parseInt(text), user);
                        editTextDialog.dismiss();
                    }
                }

                @Override
                public void onCancel() {

                }
            });
            editTextDialog.show(getChildFragmentManager(), "edit");
        }));

        back.setOnClickListener(v -> {
            title.setText("学院");
            if (recyclerView.getVisibility() == View.VISIBLE) {
                dismiss();
            } else {
                recyclerView.setVisibility(View.VISIBLE);
                recyclerView2.setVisibility(View.GONE);
            }
        });

        new Thread(this::read).start();
    }

    private void setData(int did, int sid, int classNum, User user) {
        ProgressDialog progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("正在请求。。");
        progressDialog.setCancelable(false);
        progressDialog.show();
        Map<String, Integer> map = new HashMap<>();
        map.put("did", did);
        map.put("sid", sid);
        map.put("classNum", classNum);
        String s = new Gson().toJson(map);
        UserProtocol userProtocol = RetrofitClient.getService(UserProtocol.class);
        Call<StatusResult<String>> update = userProtocol.update(user.getToken(), user.getId(), "department", s);
        HttpUtils.doRequest(update, result -> {
            progressDialog.dismiss();
            if (result == null || !result.isSuccess()) {
                if (result != null) ToastUtils.showToast(result.getMsg());
                dismiss();
                return;
            }

            UserInfo userInfo = user.getUserInfo();
            userInfo.setSpecialities(list2.get(adapter2.getSelectPosition()));
            userInfo.setDepartment(list.get(adapter.getSelectPosition()));
            UserManager.saveUser(user);
            dismiss();
            if (onFinishListener != null) {
                onFinishListener.onFinish();
            }

        });
    }

    private void read() {
        AssetManager assetManager = ResourcesManager.getRes().getAssets();
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    assetManager.open("department.json"), StandardCharsets.UTF_8));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            bufferedReader.close();
            String string = stringBuilder.toString();
            List<Department> departments = new Gson().fromJson(string, new TypeToken<List<Department>>() {
            }.getType());

            getActivity().runOnUiThread(() -> {
                Log.d(TAG, "read: ");
                list.addAll(departments);
                list2.addAll(departments.get(adapter.getSelectPosition()).getSpecialitiesList());
                adapter.notifyDataSetChanged();
                adapter2.notifyDataSetChanged();
            });
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "read: ", e);
        }
    }

}
